function $(id){
    return document.getElementById(id);
}

window.onload = function (){
    fullTable(bookArray);
}

/**
 * 填充书籍表格数据
 */
function  fullTable(bookList){
    var str = "";
    bookList.forEach(n => {
       str += `<tr><td><img src="img/${n.imgPath}" width="50" height="50"></td>
            <td>${n.name}</td><td>${n.auth}</td><td>${n.price}</td>
            <td><a href="javascript:showInfo(${n.code})">查看</a>
            <a href="javascript:addShop(${n.code})">加入购物车</a></td></tr>`;
    });
    $("bookData").innerHTML = str;
}

/**
 * 按编号查看书籍
 * @param bookCode 书籍编号
 */
function showInfo(bookCode){
    //找到编号对应的书籍对象
    var bookObj = bookArray.find(n => n.code == bookCode);
    $("nameSpan").innerHTML = bookObj.name;
    $("authSpan").innerHTML = bookObj.auth;
    $("priceSpan").innerHTML = bookObj.price;
    $("dateSpan").innerHTML = bookObj.date;
    $("bookImg").src = "img/"+bookObj.imgPath;
}

/**
 * 搜索
 */
function findBook(){
   var newList =  bookArray.filter(n => n.name.indexOf($("nameTxt").value) != -1);
   fullTable(newList);
}

//购物车集合。格式为：[{book:{code:1,name:'三国'},num:1}]
var shopArray = [];
function addShop(bookCode){
    //显示购物车弹出框
    $("shopDiv").style.visibility = "visible";
    //判断书籍编号在购物车中是否存在
    var shopObj = shopArray.find(n => n.book.code == bookCode);
    if(shopObj == null){//不存在该书籍，添加购物车元素
        var bookObj = bookArray.find(n => n.code == bookCode);
        //创建购物车对象
        shopObj = {book:bookObj,num:1};
        //加入购物车集合
        shopArray.push(shopObj);
    }
    else{
        shopObj.num ++;
    }

    showShopInfo();
}

function showShopInfo(){
    var str = "";
    var totalPrice = 0;
    shopArray.forEach(n => {
       str += `<tr><td>${n.book.name}</td><td>${n.book.price}</td>
        <td><input type="number" value="${n.num}" onblur="changeNum(this.value,${n.book.code})"></td><td>${n.book.price * n.num}</td>
        <td><input type="button" value="移除商品" onclick="removeBook(${n.book.code})"></td></tr>`;
       totalPrice += n.book.price * n.num;
    });
    $("shopData").innerHTML = str;
    $("totalPriceSpan").innerHTML = totalPrice;
}

/**
 * 继续购物
 */
function continueBuy(){
    $("shopDiv").style.visibility = 'hidden';
}

/**
 * 改变数量
 * @param newNum 新数量
 * @param code 书籍编号
 */
function changeNum(newNum,code){
    var shopObj = shopArray.find(n => n.book.code == code);
    shopObj.num = newNum;
    showShopInfo();
}

/**
 * 移除商品
 * @param bookCode 书籍编号
 */
function removeBook(bookCode){
    //找到书籍编号对应购物车对象下标
    var index = shopArray.findIndex(n => n.book.code==bookCode);
    //删除数组元素
    shopArray.splice(index,1);
    showShopInfo();
}
